
package com.kugou.game.sdk.ui.widget.indicator;

import com.kugou.framework.v4.ViewPager;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;

/**
 * 重写了setviewpager方法 已经把父类UnderlinePageIndicator的私有属性，都改成了protected
 * 描述:新增了setwidth方法，来设置下划线的长度。设置值为下划线
 * 
 * @author zhanghj
 * @since 2014-3-26 下午2:07:53
 */
public class UnderlinePageIndicatorEx extends UnderlinePageIndicator {
    private int mWidth = 1;

    /**
     * 更改下划线的宽度的比值
     */
    public void setWidth(int width) {
        this.mWidth = width;
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (mViewPager == null) {
            return;
        }
        final int count = mViewPager.getAdapter().getCount();
        if (count == 0) {
            return;
        }

        if (mCurrentPage >= count) {
            setCurrentItem(count - 1);
            return;
        }
        // 设置线宽为每个tab的宽度
        final int paddingLeft = getPaddingLeft();
        final float pageWidth = (getWidth() - paddingLeft - getPaddingRight()) / (1f * count);
        final float left = paddingLeft + pageWidth * (mCurrentPage + mPositionOffset);
        final float right = left + pageWidth;
        final float top = getPaddingTop();
        final float bottom = getHeight() - getPaddingBottom();
        if (mWidth == -1) {
            canvas.drawRect(left, top, right, bottom, mPaint);
        } else if (mWidth != 0) {
            canvas.drawRect(left + pageWidth / mWidth, top, right - pageWidth / mWidth, bottom,
                    mPaint);
        } else {
            canvas.drawRect(left + pageWidth, top, right - pageWidth, bottom, mPaint);
        }
    }

    public UnderlinePageIndicatorEx(Context context) {
        super(context, null);

    }

    public UnderlinePageIndicatorEx(Context context, AttributeSet attrs) {
        super(context, attrs, 0);

    }

    public UnderlinePageIndicatorEx(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }

    @Override
    public void setViewPager(ViewPager viewPager) {
        if (mViewPager == viewPager) {
            return;
        }
        // 此处会把tab注册的监听器给清楚掉
        // if (mViewPager != null) {
        // //Clear us from the old pager.
        // mViewPager.setOnPageChangeListener(null);
        // }
        if (viewPager.getAdapter() == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        mViewPager = viewPager;
        // 去掉此句代码，因为此处要监听的是Tabindicator的活动状况，不是viewpager
        // mViewPager.setOnPageChangeListener(this);
        invalidate();
        post(new Runnable() {
            @Override
            public void run() {
                if (mFades) {
                    post(mFadeRunnable);
                }
            }
        });
    }
}
